package com.visionblue.business.ship.util.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 项目名称：sea-client-android
 * 类描述：文件下载器
 * 创建人：dell
 * 创建时间：2019/12/1715:08
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
public class FileDownloader {
    private int lastProgress;
    private Call call;
    private static final int READ_LEN = 1024;


    public void download(String url, File file, DownloadCallBack callBack) {

        if (file != null) {
            file.getParentFile().mkdirs();
            downloadInternal(url, file, null, callBack);
        }
    }

    public void download(String url, OutputStream os, DownloadCallBack callBack) {
        if (os == null) {
            return;
        }
        downloadInternal(url, null, os, callBack);
    }

    private void downloadInternal(String url, File file, OutputStream os, DownloadCallBack callBack) {
        /*
        构造请求
         */
        OkHttpClient client = new OkHttpClient();
        NetFactory.disableSSLException(client);
        Request request = new Request.Builder()
                .url(url)
                .build();

        /*
        异步请求
         */
        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Logger.e(e.getMessage());
                if (callBack != null) {
                    callBack.onError(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) {

                InputStream is = null;
                OutputStream fos = os;

                try {

                    is = response.body().byteStream();

                    //熟悉的流读取和写入操作
                    byte[] buff = new byte[READ_LEN];
                    int len;

                    if (fos == null) {
                        fos = new FileOutputStream(file);
                    }

                    long current = 0;
                    long total = response.body().contentLength();


                    lastProgress = 0;

                    while ((len = is.read(buff)) != -1) {
                        current += len;
                        fos.write(buff, 0, len);

                        if (call != null) {
                            //计算下载进度并回调
                            int progress = (int) (current * 100 / total);
                            if (progress > lastProgress) {
                                callBack.onProgress(getFilename(), progress);
                                lastProgress = progress;
                            }
                        }
                    }

                    fos.flush();
                    response.body().close();

                    if (callBack != null) {
                        callBack.onComplete(getFilename());
                    }

                } catch (Exception e) {

                    if (call != null) {
                        callBack.onError(e);
                    }

                } finally {
                    StreamUtils.close(fos);
                    StreamUtils.close(is);
                }
            }

            private String getFilename() {
                return file == null ? "" : file.getName();
            }
        });
    }

    public void cancel() {
        if (call != null && !call.isCanceled()) {
            call.cancel();
        }
    }

}
